// pages/songs/songs.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 搜索相关
    searchKeyword: "",
    searchResults: [],
    searchLoading: false,

    // 歌手信息
    artistInfo: null,

    // 推荐歌单
    recommendPlaylists: [],

    // 推荐歌曲
    recommendedSongs: [],
    recommendedSongsGroups: [], // 分组后的推荐歌曲

    // 用户歌单
    userPlaylists: [],

    // 播放状态
    nowPlaying: {
      title: "暂无播放",
      artist: "未知歌手",
      coverUrl: "",
    },
    isPlaying: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("歌曲页面onLoad");

    // 获取全局用户信息
    const app = getApp();
    const userInfo = wx.getStorageSync("userInfo");
    console.log("本地存储用户信息:", userInfo);

    // 显示调试提示
    this.showDebugInfo();

    // 检查token
    this.checkToken();

    // 如果存在用户信息但没有token，尝试创建临时token
    if (userInfo && userInfo.userId && !wx.getStorageSync("access_token")) {
      console.log("发现用户信息但无token，创建临时token");
      this.createTemporaryToken(userInfo);
    }
  },

  /**
   * 显示调试信息
   */
  showDebugInfo: function () {
    // 显示调试信息
    try {
      const bgAudioManager = wx.getBackgroundAudioManager();
      console.log("=== 音频管理器状态 ===");
      console.log("是否存在src:", bgAudioManager.src ? "是" : "否");
      console.log("当前标题:", bgAudioManager.title || "无");
      console.log("当前歌手:", bgAudioManager.singer || "无");
      console.log("是否暂停:", bgAudioManager.paused ? "是" : "否");
      console.log("当前播放时间:", bgAudioManager.currentTime || 0);
      console.log("总时长:", bgAudioManager.duration || 0);
    } catch (error) {
      console.error("获取音频管理器信息失败:", error);
    }
  },

  /**
   * 创建临时token
   */
  createTemporaryToken: function (userInfo) {
    // 使用用户ID创建一个临时token
    const tempToken = `temp_token_${userInfo.userId}_${Date.now()}`;
    wx.setStorageSync("access_token", tempToken);
    console.log("已创建临时token:", tempToken);

    // 重新加载数据
    this.fetchRecommendPlaylists();
    this.fetchRecommendedSongs();
    this.fetchUserPlaylists();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("歌曲页面onShow");

    // 立即检查并更新当前播放状态
    setTimeout(() => {
      this.checkNowPlaying();
    }, 100);

    // 检查token状态，确保在页面显示时也能正确加载数据
    const token = wx.getStorageSync("access_token");
    const userInfo = wx.getStorageSync("userInfo");
    console.log("Songs页面onShow时检查token:", token);
    console.log("Songs页面onShow时检查userInfo:", userInfo);

    // 如果有userInfo但没有token，创建临时token
    if (userInfo && userInfo.userId && !token) {
      console.log("onShow发现用户已登录但无token，创建临时token");
      this.createTemporaryToken(userInfo);
      return;
    }

    if (token) {
      // 确保数据已加载
      this.ensureDataLoaded();
    } else {
      console.log("未检测到access_token，请先登录");
      // 如果没有token，显示登录提示，但不重置页面状态
      wx.showToast({
        title: "请先登录",
        icon: "none",
      });
    }
  },

  /**
   * 确保数据已经加载
   */
  ensureDataLoaded: function () {
    // 如果搜索结果为空，说明需要重新加载数据
    if (this.data.recommendPlaylists.length === 0) {
      console.log("加载推荐歌单数据");
      this.fetchRecommendPlaylists();
    }

    if (this.data.recommendedSongs.length === 0) {
      console.log("加载推荐歌曲数据");
      this.fetchRecommendedSongs();
    }

    if (this.data.userPlaylists.length === 0) {
      console.log("加载用户歌单数据");
      this.getUserId(); // 获取用户ID
      this.fetchUserPlaylists();
    }
  },

  /**
   * 检查Token并获取数据
   */
  checkToken: function () {
    const token = wx.getStorageSync("access_token");
    console.log("当前token状态:", token ? "已存在" : "不存在");

    if (!token) {
      // 尝试从userInfo中提取用户ID
      const userInfo = wx.getStorageSync("userInfo");
      if (userInfo && userInfo.userId) {
        // 用户已登录但没有token，创建临时token
        this.createTemporaryToken(userInfo);
        return;
      }

      // 真的没有登录信息
      wx.showToast({
        title: "请先登录",
        icon: "none",
      });
      return;
    }

    // 尝试获取用户ID
    this.getUserId();

    // 加载所有数据
    this.fetchRecommendPlaylists();
    this.fetchRecommendedSongs();
    this.fetchUserPlaylists();
  },

  /**
   * 获取推荐歌单
   */
  fetchRecommendPlaylists: function () {
    const token = wx.getStorageSync("access_token");
    const that = this;

    wx.request({
      url: "https://smartsound.top/personalized",
      method: "GET",
      data: {
        limit: 10,
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        console.log("推荐歌单:", res.data);
        if (res.data && res.data.result) {
          that.setData({
            recommendPlaylists: res.data.result,
          });
        }
      },
      fail(err) {
        console.error("获取推荐歌单失败:", err);
      },
    });
  },

  /**
   * 获取推荐歌曲
   */
  fetchRecommendedSongs: function () {
    const token = wx.getStorageSync("access_token");
    const that = this;

    wx.request({
      url: "https://smartsound.top/personalized/newsong",
      method: "GET",
      data: {
        limit: 9,
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        console.log("推荐歌曲:", res.data);
        if (res.data && res.data.result) {
          // 处理歌曲数据
          const songs = res.data.result.map((item) => {
            return {
              id: item.id,
              name: item.name,
              artist: item.song.artists[0].name,
              picUrl: item.picUrl || item.song.album.picUrl,
              album: item.song.album.name,
            };
          });

          // 将歌曲分成3组，每组3首歌
          const groups = [];
          for (let i = 0; i < songs.length; i += 3) {
            groups.push(songs.slice(i, i + 3));
          }

          that.setData({
            recommendedSongs: songs,
            recommendedSongsGroups: groups,
          });
        }
      },
      fail(err) {
        console.error("获取推荐歌曲失败:", err);
      },
    });
  },

  /**
   * 获取用户歌单
   */
  fetchUserPlaylists: function () {
    const token = wx.getStorageSync("access_token");
    const that = this;

    // 获取用户ID
    const userId = this.getUserId();
    if (!userId) {
      console.log("未获取到用户ID，无法获取用户歌单");
      return;
    }

    wx.request({
      url: "https://smartsound.top/user/playlist",
      method: "GET",
      data: {
        uid: userId,
        limit: 10,
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        console.log("用户歌单:", res.data);
        if (res.data && res.data.playlist) {
          that.setData({
            userPlaylists: res.data.playlist,
          });
        }
      },
      fail(err) {
        console.error("获取用户歌单失败:", err);
      },
    });
  },

  /**
   * 搜索歌曲
   */
  searchSongs: function (keywords) {
    const token = wx.getStorageSync("access_token");
    if (!token) {
      wx.showToast({
        title: "请先登录",
        icon: "none",
      });
      this.setData({ searchLoading: false });
      return;
    }

    const that = this;
    this.setData({ searchLoading: true });

    wx.request({
      url: "https://smartsound.top/cloudsearch",
      method: "GET",
      data: {
        keywords: keywords,
        limit: 30,
        type: 1,
        offset: 0,
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        that.setData({ searchLoading: false });
        console.log("搜索返回数据:", res.data);

        if (res.data && res.data.result && res.data.result.songs) {
          // 处理搜索结果
          const songs = res.data.result.songs.map((song) => {
            return {
              id: song.id,
              name: song.name,
              artists: song.ar || song.artists,
              album: song.al || song.album,
              picUrl:
                (song.al && song.al.picUrl) ||
                (song.album && song.album.picUrl) ||
                "",
            };
          });

          that.setData({ searchResults: songs });

          // 检查是否有匹配的歌手
          that.checkForArtist(keywords);
        }
      },
      fail(err) {
        that.setData({ searchLoading: false });
        console.error("搜索失败:", err);
      },
    });
  },

  /**
   * 检查是否有匹配的歌手
   */
  checkForArtist: function (keywords) {
    const token = wx.getStorageSync("access_token");
    if (!token) {
      console.log("未登录，跳过歌手搜索");
      return;
    }

    const that = this;

    wx.request({
      url: "https://smartsound.top/cloudsearch",
      method: "GET",
      data: {
        keywords: keywords,
        limit: 5,
        type: 100, // 100表示搜索歌手
        offset: 0,
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        console.log("歌手搜索结果:", res.data);

        if (
          res.data &&
          res.data.result &&
          res.data.result.artists &&
          res.data.result.artists.length > 0
        ) {
          // 取第一个匹配的歌手
          const artist = res.data.result.artists[0];
          that.setData({
            artistInfo: artist,
          });
        } else {
          that.setData({ artistInfo: null });
        }
      },
      fail(err) {
        console.error("歌手搜索失败:", err);
      },
    });
  },

  /**
   * 检查当前播放的歌曲
   */
  checkNowPlaying: function () {
    const app = getApp();
    const bgAudioManager = wx.getBackgroundAudioManager();

    // 检查当前是否有歌曲在播放
    const hasSong = bgAudioManager.src && bgAudioManager.src.length > 0;
    const isPlaying = hasSong && !bgAudioManager.paused;

    console.log(
      "当前播放状态:",
      hasSong ? "有歌曲" : "无歌曲",
      isPlaying ? "正在播放" : "已暂停"
    );

    // 从全局数据更新本地数据
    if (
      app.globalData &&
      app.globalData.nowPlaying &&
      app.globalData.nowPlaying.id
    ) {
      this.setData({
        nowPlaying: app.globalData.nowPlaying,
        isPlaying: isPlaying,
      });
    }

    // 注册播放状态变化回调
    app.playStatusCallback = (isPlaying) => {
      console.log("播放状态变化:", isPlaying ? "播放" : "暂停");
      this.setData({ isPlaying });
    };

    // 注册歌曲变化回调
    app.songChangeCallback = (song) => {
      console.log("歌曲变化:", song.title);
      this.setData({
        nowPlaying: song,
        isPlaying: true,
      });
    };
  },

  /**
   * 搜索输入处理
   */
  onSearchInput: function (e) {
    this.setData({
      searchKeyword: e.detail.value,
    });

    // 如果输入为空，清空搜索结果
    if (!e.detail.value) {
      this.setData({
        searchResults: [],
        artistInfo: null,
      });
      return;
    }

    // 否则进行搜索
    this.searchSongs(e.detail.value);
  },

  /**
   * 清空搜索框
   */
  clearSearch: function () {
    this.setData({
      searchKeyword: "",
      searchResults: [],
      artistInfo: null,
    });
  },

  /**
   * 处理歌曲点击
   */
  handleSongTap: function (e) {
    const songId = e.currentTarget.dataset.id;
    const songName = e.currentTarget.dataset.name;
    const songInfo = this.getSelectedSong(songId);

    console.log("点击歌曲:", songId, songName);

    if (!songInfo) {
      console.error("无法获取歌曲信息");
      return;
    }

    // 获取全局app
    const app = getApp();

    // 如果已有播放列表，则先保存
    if (!app.globalData.currentSongList) {
      app.globalData.currentSongList = [];
    }

    // 将当前搜索结果或推荐歌曲列表设置为播放列表
    if (this.data.searchResults.length > 0) {
      app.globalData.currentSongList = [...this.data.searchResults];
    } else if (this.data.recommendedSongs.length > 0) {
      app.globalData.currentSongList = [...this.data.recommendedSongs];
    }

    // 确保歌曲时长信息存在
    if (!songInfo.dt && songInfo.duration) {
      songInfo.dt = songInfo.duration * 1000;
    }

    // 播放选中的歌曲
    app.playSong(songInfo);

    // 更新本地播放状态
    this.setData({
      nowPlaying: {
        id: songInfo.id,
        title: songInfo.name,
        artist:
          songInfo.artist ||
          (songInfo.ar && songInfo.ar[0].name) ||
          (songInfo.artists && songInfo.artists[0].name) ||
          "未知歌手",
        coverUrl:
          songInfo.picUrl ||
          (songInfo.al && songInfo.al.picUrl) ||
          (songInfo.album && songInfo.album.picUrl) ||
          "",
      },
      isPlaying: true,
    });

    // 跳转到歌曲详情页
    wx.navigateTo({
      url: `/pages/song/song?id=${songId}&name=${encodeURIComponent(songName)}`,
    });
  },

  /**
   * 获取被选中的歌曲信息
   */
  getSelectedSong: function (songId) {
    // 先从搜索结果中查找
    if (this.data.searchResults && this.data.searchResults.length > 0) {
      const found = this.data.searchResults.find((song) => song.id == songId);
      if (found) return found;
    }

    // 再从推荐歌曲中查找
    if (this.data.recommendedSongs && this.data.recommendedSongs.length > 0) {
      const found = this.data.recommendedSongs.find(
        (song) => song.id == songId
      );
      if (found) return found;
    }

    // 如果都找不到，构建一个基本的歌曲信息对象
    return {
      id: songId,
      name: "未知歌曲",
      artist: "未知歌手",
      picUrl: "",
    };
  },

  /**
   * 处理歌手点击
   */
  handleArtistTap: function (e) {
    const artistId = e.currentTarget.dataset.id;
    const artistInfo = this.data.artistInfo;

    console.log("点击歌手:", artistId, artistInfo.name);

    // 跳转到歌手详情页
    wx.navigateTo({
      url: `/pages/artist/artist?id=${artistId}&name=${encodeURIComponent(
        artistInfo.name
      )}`,
    });
  },

  /**
   * 处理歌单点击
   */
  handlePlaylistTap: function (e) {
    const playlistId = e.currentTarget.dataset.id;
    const playlistName = e.currentTarget.dataset.name;

    console.log("点击歌单:", playlistId, playlistName);

    // 跳转到歌单详情页
    wx.navigateTo({
      url: `/pages/playlist/playlist?id=${playlistId}&name=${encodeURIComponent(
        playlistName
      )}`,
    });
  },

  /**
   * 切换播放状态
   */
  togglePlayState: function (e) {
    // 阻止冒泡，防止触发父元素的点击事件
    // 只有当e是有效的事件对象时才调用stopPropagation
    if (e && typeof e.stopPropagation === "function") {
      e.stopPropagation();
    }

    console.log("触发播放/暂停按钮");

    // 获取全局app实例
    const app = getApp();

    // 获取背景音频管理器
    const bgAudioManager = wx.getBackgroundAudioManager();

    // 显示调试信息
    console.log("音频管理器信息:", {
      src: bgAudioManager.src ? "有音频" : "无音频",
      paused: bgAudioManager.paused ? "已暂停" : "播放中",
      currentTime: bgAudioManager.currentTime || 0,
      duration: bgAudioManager.duration || 0,
      title: bgAudioManager.title || "无标题",
    });

    // 检查是否有正在播放的音频
    if (!bgAudioManager.src) {
      wx.showToast({
        title: "暂无播放歌曲",
        icon: "none",
        duration: 1500,
      });
      return;
    }

    // 根据当前播放状态执行相反操作
    const isCurrentlyPlaying = !bgAudioManager.paused;

    if (isCurrentlyPlaying) {
      // 当前在播放，执行暂停
      try {
        console.log("执行暂停操作");
        bgAudioManager.pause();

        // 更新UI状态
        this.setData({ isPlaying: false });

        // 反馈给用户
        wx.showToast({
          title: "已暂停",
          icon: "none",
          duration: 1000,
        });

        // 同步全局状态
        if (app && app.globalData) {
          app.globalData.isPlaying = false;
        }
      } catch (error) {
        console.error("暂停操作失败:", error);
      }
    } else {
      // 当前已暂停，执行播放
      try {
        console.log("执行播放操作");
        bgAudioManager.play();

        // 更新UI状态
        this.setData({ isPlaying: true });

        // 反馈给用户
        wx.showToast({
          title: "播放中",
          icon: "none",
          duration: 1000,
        });

        // 同步全局状态
        if (app && app.globalData) {
          app.globalData.isPlaying = true;
        }
      } catch (error) {
        console.error("播放操作失败:", error);
      }
    }
  },

  /**
   * 获取用户ID
   */
  getUserId: function () {
    // 首先尝试从缓存获取
    const userId = wx.getStorageSync("userId");
    if (userId) {
      console.log("从缓存获取用户ID:", userId);
      return userId;
    }

    // 然后尝试从userInfo获取
    const userInfo = wx.getStorageSync("userInfo");
    if (userInfo && userInfo.userId) {
      const userId = userInfo.userId;
      console.log("从userInfo获取用户ID:", userId);
      // 保存到缓存中方便下次使用
      wx.setStorageSync("userId", userId);
      return userId;
    }

    // 获取不到用户ID时，尝试通过登录获取
    console.log("无法获取用户ID，尝试登录获取");
    this.loginAndGetUserId();
    return null;
  },

  /**
   * 登录并获取用户ID
   */
  loginAndGetUserId: function () {
    const that = this;
    console.log("开始登录流程获取用户ID");

    wx.login({
      success(res) {
        if (res.code) {
          console.log("获取微信登录code成功:", res.code);
          // 发送 res.code 到后台换取 openId 和 userId
          wx.request({
            url: "https://smartsound.top/user/login",
            method: "POST",
            data: {
              code: res.code,
            },
            success(res) {
              console.log("登录成功，用户信息:", res.data);
              if (res.data && res.data.userId) {
                // 存储用户ID
                const userId = res.data.userId;
                wx.setStorageSync("userId", userId);
                console.log("成功获取并保存用户ID:", userId);

                // 如果没有access_token，创建一个
                if (!wx.getStorageSync("access_token")) {
                  const tempToken = `temp_token_${userId}_${Date.now()}`;
                  wx.setStorageSync("access_token", tempToken);
                  console.log("已创建临时token:", tempToken);
                }

                // 获取用户歌单
                that.fetchUserPlaylists();
              }
            },
            fail(err) {
              console.error("登录失败:", err);
            },
          });
        } else {
          console.error("获取登录凭证失败:", res.errMsg);
        }
      },
      fail(err) {
        console.error("微信登录接口调用失败:", err);
      },
    });
  },

  /**
   * 处理正在播放栏点击
   */
  handleNowPlayingTap: function () {
    if (this.data.nowPlaying.id) {
      // 跳转到歌曲详情页
      wx.navigateTo({
        url: `/pages/song/song?id=${
          this.data.nowPlaying.id
        }&name=${encodeURIComponent(this.data.nowPlaying.title)}`,
      });
    }
  },

  /**
   * 查看更多推荐歌曲
   */
  viewMoreRecommendedSongs: function () {
    wx.navigateTo({
      url: "/pages/recommended-songs/recommended-songs",
    });
  },

  /**
   * 查看更多用户歌单
   */
  viewMoreUserPlaylists: function () {
    wx.navigateTo({
      url: "/pages/userPlaylists/userPlaylists",
    });
  },

  /**
   * 刷新推荐歌曲
   */
  refreshRecommendedSongs: function () {
    // 显示加载提示
    wx.showLoading({
      title: "刷新中...",
      mask: true,
    });

    const token = wx.getStorageSync("access_token");
    const that = this;

    // 判断是否已经有缓存的更多推荐歌曲
    const cachedSongs = wx.getStorageSync("allRecommendedSongs");

    if (cachedSongs && cachedSongs.length > 9) {
      // 如果有缓存的歌曲，随机打乱并显示9首
      const shuffledSongs = this.shuffleArray(cachedSongs);
      const selectedSongs = shuffledSongs.slice(0, 9);

      that.setData({
        recommendedSongs: selectedSongs,
      });

      wx.showToast({
        title: "刷新成功",
        icon: "success",
        duration: 1500,
      });

      wx.hideLoading();
      return;
    }

    // 如果没有缓存的歌曲，请求更多歌曲（获取30首）
    let apiUrl = "https://smartsound.top/personalized/newsong";
    let params = {
      limit: 30,
      timestamp: Date.now(),
    };

    wx.request({
      url: apiUrl,
      method: "GET",
      data: params,
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        console.log("获取更多推荐歌曲:", res.data);

        let songs = [];
        if (res.data && res.data.result) {
          // 处理返回的数据
          songs = res.data.result.map((item) => {
            return {
              id: item.id,
              name: item.name,
              artist: item.song.artists[0].name,
              picUrl: item.picUrl || item.song.album.picUrl,
              album: item.song.album.name,
            };
          });

          // 缓存所有歌曲
          wx.setStorageSync("allRecommendedSongs", songs);

          // 随机打乱并选择9首显示
          const shuffledSongs = that.shuffleArray(songs);
          const selectedSongs = shuffledSongs.slice(0, 9);

          that.setData({
            recommendedSongs: selectedSongs,
          });

          wx.showToast({
            title: "刷新成功",
            icon: "success",
            duration: 1500,
          });
        } else {
          // 如果没有获取到歌曲，显示错误提示
          wx.showToast({
            title: "没有获取到推荐歌曲",
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail(err) {
        console.error("刷新推荐歌曲失败:", err);
        // 显示失败提示
        wx.showToast({
          title: "刷新失败",
          icon: "none",
          duration: 1500,
        });
      },
      complete() {
        // 隐藏加载提示
        wx.hideLoading();
      },
    });
  },

  /**
   * 数组随机打乱（Fisher-Yates洗牌算法）
   */
  shuffleArray: function (array) {
    const newArray = [...array]; // 创建副本，不修改原数组
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]]; // 交换元素
    }
    return newArray;
  },
});
